#include "FileLog.h"

#include "recovery/fs/Path.h"
#include "recovery/fs/file/File.h"
#include "recovery/fs/file/FileLogOperation.h"

namespace recovery {
namespace log {

const std::string FileLog::DefaultDir = ".";
const std::string FileLog::DefaultName = "log";

FileLog::FileLog(const std::string & name, const std::string & dir)
: _name(name.empty() ? DefaultName : name)
, _dir(dir.empty() ? DefaultDir : dir)
, _path(recovery::fs::Path::from(_dir, _name))
{
}
FileLog::~FileLog() {
}
int FileLog::size() const {
    size_t sz = 0;
    return operation->size(sz) ? sz : -1;
}
int FileLog::remove() {
    return operation->remove() ? 0 : -1;
}
int FileLog::truncate(size_t size) {
    return operation->truncate(size) ? 0 : -1;
}
int FileLog::sync() {
    if(isOpen()){
        return operation->sync() ? 0 : -1;
    }
    return -1;
}
int FileLog::append(const std::string & data) {
    if(isOpen()){
        size_t writedBytes = 0;
        return operation->write(data, writedBytes) ? writedBytes : -1;
    }
    return -1;
}
int FileLog::positionedRead(const size_t offset, uint8_t * buf, const int len) {
    if(isOpen()){
        size_t readBytes = 0;
        return operation->positionedRead(offset, buf, len, readBytes) ? readBytes : -1;
    }
    return -1;
}
int FileLog::openOnce() {
    recovery::fs::file::File f(_path);
    if(f.exist()){
        return recovery::fs::file::FileLogOperation::openExist(_path, operation) ? 0 : -1;
    }
    else{
        return recovery::fs::file::FileLogOperation::create(_path, operation) ? 0 : -1;
    }
}
int FileLog::closeOnce() {
    return operation->close() ? 0 : -1;
}

} //end of namespace log
} //end of namespace recovery
